package com.wcs.exam.dao.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.wcs.exam.common.base.page.SqlUtil;
import com.wcs.exam.dao.QuestionOptionDao;
import com.wcs.exam.dao.impl.mapper.entity.QuestionOption;
import com.wcs.exam.dao.impl.mapper.QuestionOptionMapper;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 试题选项 持久化实现类
 *
 * @author wcs
 * @since 2025-03-11
 */
@Repository
public class QuestionOptionDaoImpl extends ServiceImpl<QuestionOptionMapper, QuestionOption> implements QuestionOptionDao {

    @Override
    public <R> List<R> selectObjs(Wrapper<QuestionOption> wrapper, Class<R> classType) {
        List<Map<String, Object>> resultMaps = baseMapper.selectMaps(wrapper);
        if (CollectionUtil.isEmpty(resultMaps)) {
            return Collections.emptyList();
        }
        return BeanUtil.copyToList(resultMaps, classType);
    }

    @Override
    public Integer getMaxSort() {
        return lambdaQuery().orderByDesc(QuestionOption::getSort).last(SqlUtil.limitOne()).oneOpt().map(QuestionOption::getSort).orElse(0);
    }

    @Override
    public List<QuestionOption> listByQuestionId(Long questionId) {
        return lambdaQuery()
                .eq(QuestionOption::getQuestionId, questionId)
                .orderByAsc(QuestionOption::getSort)
                .orderByAsc(QuestionOption::getId)
                .list();
    }

    @Override
    public List<QuestionOption> listByQuestionIds(Collection<Long> questionIds) {
        return lambdaQuery()
                .in(QuestionOption::getQuestionId, questionIds)
                .orderByAsc(QuestionOption::getQuestionId)
                .orderByAsc(QuestionOption::getSort)
                .orderByAsc(QuestionOption::getId)
                .list();
    }

    @Override
    public boolean deleteByQuestionId(Long questionId) {
        return lambdaUpdate()
                .eq(QuestionOption::getQuestionId, questionId)
                .remove();
    }

    @Override
    public boolean deleteByQuestionIds(Collection<Long> questionIds) {
        return lambdaUpdate()
                .in(QuestionOption::getQuestionId, questionIds)
                .remove();
    }
}
